package com.miao.common.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.miao.common.entity.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author MiaoWenqing
 * @description: 文件上传 类
 * @date 2021/1/18 21:59
 */

@RestController
public class FileUpload {

    @PostMapping(value = "/common/upload")
    public R fileUpload(MultipartFile file) throws IOException {

        String uuid = UUID.randomUUID().toString().replace("-", "");

        //给上传的文件重新命名避免出现重名
        String filename = uuid + "_" + System.currentTimeMillis()+".";



        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = "LTAI4G33G9Yy6XV5GtYZ5a5P";
        String accessKeySecret = "HIZki9VhpYD6Qq9bOjYLaCPnkDNLJ5";


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建PutObjectRequest对象。
        // <yourObjectName>表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        PutObjectRequest putObjectRequest = new PutObjectRequest("huangshen", "miao-shop/img/"+filename+"png", new ByteArrayInputStream(file.getBytes()));


        // 上传字符串。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();
        HashMap<String, Object> res = new HashMap<>();
        res.put("url","https://huangshen.oss-cn-beijing.aliyuncs.com/miao-shop/img/"+filename+"png");


        return new R(2000,"上传成功",res);

    }

}
